<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 1-->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span
          style="color: red;">注：1.上报材料：应提供盖所公章已签订的任务书复印件（无任务书需提供说明）及项目文本模板，并按非财项目小计提供汇总模板，所有提供的科研项目申报资料，需由科研处审核盖章并经分管领导签字。
          2.所有2026年收到以后年度项目资金的，以2026年预算支出对应填列2026年项目收入。
          单位： 万元
        </span>
        <a-row>
          <!--          <a-col :xs="24" :sm="12">-->
          <!--            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit">-->
          <!--              <j-dict-select-tag type="list" v-model="model.unit" dictCode="unit" placeholder="请选择单位" />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择年度"
                @change="handleYearChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="项目支出收入支出表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table :ref="refKeys[0]" :loading="cwXmzcsrbTable.loading" :columns="cwXmzcsrbTable.columns"
          :dataSource="cwXmzcsrbTable.dataSource" :maxHeight="300" :disabled="formDisabled" :rowNumber="true"
          :rowSelection="true" :actionButton="true" />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { mapState } from 'vuex'

import { FormTypes, getRefPromise, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
import { validateDuplicateValue } from '@/utils/util'
import { getAction } from '@/api/manage'

export default {
  name: 'CwXmzcsrbTjForm',
  mixins: [JEditableTableModelMixin],
  components: {},
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: { year: '' }, // 初始为空，由watch同步全局年度
      validatorRules: {
        unit: [
          { required: true, message: '请选择单位!' },
        ],
        year: [
          { required: true, message: '请选择年度!' },
        ],
      },
      addDefaultRowNum: 1,
      refKeys: ['cwXmzcsrb'],
      tableKeys: ['cwXmzcsrb'],
      activeKey: 'cwXmzcsrb',
      confirmLoading: false,
      // 项目支出收入支出表
      cwXmzcsrbTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '项目',
            key: 'project',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '财政非财政',
            key: 'czFcz',
            type: FormTypes.select,
            dictCode: "cz_fcz",
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '上年结转',
            key: 'snjz',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],

          },
          {
            title: '财政资金',
            key: 'financialFund',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '事业收入',
            key: 'undertakingRevenue',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '其他收入',
            key: 'otherRevenue',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '非财政拨款结余',
            key: 'fczbkjy',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '项目支出',
            key: 'projectExpenditure',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '0.0',
            validateRules: [
              {
                // 修改后的正则：仅允许非负数字，支持整数或最多2位小数
                pattern: /^\d+(\.\d{1,2})?$/,
                message: "${title}格式不正确，仅支持非负整数或最多2位小数"
              }
            ],
          },
          {
            title: '备注',
            key: 'remark',
            type: FormTypes.input,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ]
      },
      url: {
        add: "/cw/cwXmzcsrbTj/add",
        edit: "/cw/cwXmzcsrbTj/edit",
        cwXmzcsrb: {
          list: '/cw/cwXmzcsrbTj/queryCwXmzcsrbByMainId'
        },
        getByYear: '/cw/cwXmzcsrbTj/list' // 复用CwTjForm的年度查询接口
      },
      isManualChange: false // 标记是否手动修改过表单年度

    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    scene: { // 接收 Modal 传递的场景值
      type: String,
      default: ''
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    ...mapState({ globalYear: state => state.app.globalYear })

  },


  watch: {
    // 监听全局年度变化，同步到表单（仅当未手动修改时）
    globalYear(newVal) {
      if (!this.isManualChange) {
        this.model.year = newVal
        // 可选：自动触发年度查询，解开注释即可
        // this.handleYearChange(newVal)
      }
    },
    // 监听表单年度变化，标记是否手动修改
    'model.year'(newVal, oldVal) {
      if (oldVal && newVal !== this.globalYear) {
        this.isManualChange = true // 手动修改后，不再同步全局年度
      }
    }
  },

  created() {
    // 初始化时同步全局年度
    this.model.year = this.globalYear
    const scene = this.scene; // 接收 Modal 传递的 scene（add/edit）
    this.currentScene = scene; // 存储到本地变量，后续复用
    console.log(scene)
    if (scene=='add'){
      this. handleYearChange(this.model.year)
    }
  },
  methods: {
    addBefore() {
      this.cwXmzcsrbTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    editAfter() {
      this.$nextTick(() => { })
      if (this.model.id) {
        let params = { id: this.model.id }
        getAction(this.url.cwXmzcsrb.list, params).then(res => {
          if (res.success) {
            this.cwXmzcsrbTable.dataSource = res.result.records || []
          }
        }).finally(() => {
          this.cwXmzcsrbTable.loading = false
        })
      }
    },
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main,
        cwXmzcsrbList: allValues.tablesValue[0].values,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    close() {
      this.visible = false
      this.$emit('close')
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    updateTableColumnTitles(selectYear) {
      // 验证输入的年份是否有效
      if (!selectYear || isNaN(selectYear) || selectYear.toString().length !== 4) {
        console.warn('无效的年份值:', selectYear);
        return;
      }

      try {
        if (!this.cwXmzcsrbTable || !this.cwXmzcsrbTable.columns) {
          console.warn('表格列配置不存在');
          return;
        }

        const columns = JSON.parse(JSON.stringify(this.cwXmzcsrbTable.columns));
        const expenditureColumn = columns.find(col => col.key === 'projectExpenditure');
        if (expenditureColumn) {
          if (!expenditureColumn.originalTitle) {
            expenditureColumn.originalTitle = expenditureColumn.title;
          }
          expenditureColumn.title = `${selectYear}年项目支出`;
          expenditureColumn.placeholder = `请输入${expenditureColumn.title}`;
        } else {
          console.warn('未找到projectExpenditure列');
        }
        this.$set(this.cwXmzcsrbTable, 'columns', columns);
      } catch (error) {
        console.error('更新表格列标题失败:', error);
        this.$message.error('更新表格信息失败，请重试');
      }
    },
    async handleYearChange(year) {
      // 清空逻辑：未选择年度时，保留单位，清空其他数据
      if (!year) {
        this.model = { unit: this.model.unit }
        this.cwXmzcsrbTable.dataSource = []
        return
      }

      // 更新表格列标题
      this.updateTableColumnTitles(year);

      // 加载状态：主表+子表同时加载
      this.confirmLoading = true
      this.cwXmzcsrbTable.loading = true

      try {
        // 调用年度查询接口
        const yearResponse = await getAction(this.url.getByYear, { year })

        if (yearResponse.success && yearResponse.result.records.length > 0) {
          const mainRecord = yearResponse.result.records[0]
          // 主表数据回显：保留用户已选的unit和year，合并接口返回的其他字段
          this.model = {
            ...this.model,
            ...mainRecord
          }

          // 使用返回的mainId调用子表列表接口
          if (mainRecord.id) {
            const subResponse = await getAction(this.url.cwXmzcsrb.list, {
              id: mainRecord.id
            })

            if (subResponse.success) {
              this.cwXmzcsrbTable.dataSource = subResponse.result.records || []
            } else {
              this.$message.warning('获取项目支出数据失败：' + (subResponse.message || '未知错误'))
              this.cwXmzcsrbTable.dataSource = []
            }
          } else {
            this.$message.warning('未获取到关联ID，无法加载项目支出数据')
            this.cwXmzcsrbTable.dataSource = []
          }
        } else {
          // 接口返回失败（如无数据），显示警告并清空子表
          this.$message.warning(yearResponse.message || '该年度暂无数据')
          this.cwXmzcsrbTable.dataSource = []
          this.model.id = undefined;

        }
      } catch (error) {
        // 异常处理
        console.error('查询接口异常：', error)
        this.$message.error('查询失败，请刷新页面重试或联系管理员')
        this.cwXmzcsrbTable.dataSource = []
      } finally {
        // 关闭加载状态（无论成功/失败）
        this.confirmLoading = false
        this.cwXmzcsrbTable.loading = false
      }
    }
  }
}
</script>

<style scoped></style>